package diva.canvaslibrary.client.particles;

import com.google.gwt.canvas.client.Canvas;
import com.google.gwt.canvas.dom.client.Context2d;
import com.google.gwt.canvas.dom.client.CssColor;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;

import java.util.List;

import static diva.lib.lang.Lang.list;
import static diva.lib.lang.Lang.schedule;

import diva.gwtlib.client.view.View;
import diva.lib.lang.Lang.Work;
import diva.lib.lang.Run;

public class SceneImpl extends View<Canvas> implements Run, Scene {

  private static final String DEFAULT_REDRAW_COLOR = "255,255,255,0.3";
  private Context2d buffer2D;
  private final Canvas canvas;
  private Context2d canvas2D;
  private final Canvas canvasBuffer;
  private final List<Object2D> objects = list();
  private CssColor redrawColor;
  private Work work;
  private int refresh = 50;
  private Size size;

  public SceneImpl(Size size) {
    setRedrawColor(DEFAULT_REDRAW_COLOR);
    canvas = Canvas.createIfSupported();
    canvas.addFocusHandler(new FocusHandler() {
      public void onFocus(FocusEvent event) {
        canvas.setFocus(false);
      }
    });
    canvasBuffer = Canvas.createIfSupported();
    initWidget(canvas);
    setSize(size);
  }

  public void add(Object2D object) {
    object.setScreenSize(size);
    objects.add(object);
  }

  public void run() {
    buffer2D.setFillStyle(redrawColor);
    buffer2D.fillRect(0, 0, getWidth(), getHeight());
    for (Object2D object : objects)
      object.draw(buffer2D);
    canvas2D.drawImage(buffer2D.getCanvas(), 0, 0);
  }

  public void setRedrawColor(String rgb) {
    redrawColor = CssColor.make("rgba(" + rgb + ")");
  }

  public void setRefresh(int refresh) {
    this.refresh = refresh;
    work.stop();
    work = schedule(refresh, this);
  }

  @Override
  public void show() {
    work = schedule(refresh, this);
    work.start();
    super.show();
  }

  private void setSize(Size size) {
    this.size = size;
    super.setSize(size.getWith(), size.getHeight());
    canvas.setCoordinateSpaceWidth(size.getWith());
    canvas.setCoordinateSpaceHeight(size.getHeight());
    canvasBuffer.setCoordinateSpaceWidth(size.getWith());
    canvasBuffer.setCoordinateSpaceHeight(size.getHeight());
    canvas2D = canvas.getContext2d();
    buffer2D = canvasBuffer.getContext2d();
  }

}
